import _pick from 'lodash/pick'
import _assign from 'lodash/assign'
import _isEmpty from 'lodash/isEmpty'
import ajax from "./ajax"
import apis from '@/service/api'
import {
	API_CONFIG
} from "@/config"

class MakeApi {
	constructor(options) {
		// 最后的返回的
		this.api = {}
		this.apiBuilder(options)
	}
	apiBuilder({
		sep = '/',
		basePath = '',
		config = {}
	}) {
		Object.keys(config).map(namespace => {
			this._apiSingleBuilder({
				namespace,
				sep,
				config: config[namespace],
				basePath
			})
		})
	}
	_apiSingleBuilder({
		namespace,
		sep = '/',
		config = {},
		basePath
	}) {
		config.forEach(api => {
			const {
				name,
				desc,
				params,
				method,
				url
			} = api
			// user.js 里面名字为 logon 的接口 那名字为 user/login 请求 
			Object.defineProperty(this.api, `${namespace.toLowerCase()}${sep}${name}`, {
				value(outerParams, outerOptions) {
					const data = _isEmpty(outerParams) ? params : _pick(_assign({}, params, outerParams), Object.keys(params))
					const _options = {
						url: basePath + url,
						desc,
						method,
						data
					}
					return ajax(_options);
				}
			})
		})
	}
}

export default new MakeApi({
	config: apis,
	...API_CONFIG
})['api']
